/*
 * All Rights Reserved.
 *
 * Author : Madhur Raj
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include "structs.h"
#include "readfile.h"

/* Forward declarations */
extern void readfile();

Node *front, *tail;

Node* getListNode ()
{
   Node *newNode = (Node*)malloc(sizeof(Node));
   if (front == NULL)
   {
      front = tail = newNode;
      newNode->next = newNode->prev = NULL;
   }
   else
   {
      tail->next = newNode;
      newNode->prev = tail;
      tail = newNode;
   }

   return (newNode);
}

int* getNode()
{
   Node *newNode = getListNode();

   return (&(newNode->data));
}

void printNodes()
{
   Node *tmp = front;

   while(tmp)
   {
      printf("%d\n", tmp->data);
      tmp = tmp->next;
   }
}

void bubbleSortRev()
{
   Node *tmp, *tmp1;

   tmp = tmp1 = front;

   for(; tmp; tmp=tmp->next)
   {
      for(; tmp1->next; tmp1=tmp1->next)
      {
         if (tmp1->data < tmp1->next->data)
         {
            SWAP(&tmp1->data, &tmp1->next->data);
         }
      }
      tmp1 = front;
   }
}


void bubbleSort()
{
   Node *tmp, *tmp1;

   tmp = tmp1 = front;

   for(; tmp; tmp=tmp->next)
   {
      for(; tmp1->next; tmp1=tmp1->next)
      {
         if (tmp1->data > tmp1->next->data)
         {
            SWAP(&tmp1->data, &tmp1->next->data);
         }
      }
      tmp1 = front;
   }
}

int main()
{
   struct timeval start, finish;
   int count = COUNT;
   front = tail = NULL;
   readfile();
#ifdef DEBUG
   printNodes();
#endif
   gettimeofday(&start, NULL);
   do
   {
      bubbleSort();
      bubbleSortRev();
   } while(--count);
   gettimeofday(&finish, NULL);
   printTime(&start, &finish);

#ifdef DEBUG
   printNodes();
#endif
   return(0);
}
